<!-- SimpleFileUpload.vue -->
<template>
  <el-upload
    class="inline-block"
    action="#"
    :show-file-list="false"
    :auto-upload="false"
    :on-change="handleImmediateUpload"
    :http-request="customUpload"
    :limit="1"
    :file-list="fileList"
  >
    <el-button
      type="primary"
      size="default"
    >
      <el-icon><upload /></el-icon>
      上传模板文件
    </el-button>

    <template #tip>
      <!-- <div class="upload-tip">{{ tipText }}</div> -->
      <el-progress
        v-if="progressVisible"
        :percentage="progressPercent"
        :status="progressStatus"
        stroke-width="15"
      />
    </template>
  </el-upload>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { ElMessage, type UploadFile, type UploadProps } from "element-plus";
import fileApi from "@/apis/fileApi";

interface Props {
  url: string; // 上传接口地址
  maxSize?: number; // 文件最大尺寸(MB)
  fileTypes?: string[]; // 允许的文件类型
  tip?: string; // 自定义提示文字
}

const props = withDefaults(defineProps<Props>(), {
  maxSize: 10,
  fileTypes: () => ["image/*", "application/pdf"],
  headers: () => ({}),
  tip: "",
});

const fileList = ref<UploadFile[]>([])
// 上传状态
const progressPercent = ref(0);
const progressVisible = ref(false);
const progressStatus = ref<"success" | "exception" | "">("");

// 动态提示文本
const tipText = computed(() => {
  if (props.tip) return props.tip;
  const types = props.fileTypes
    .join(", ")
    .replace("image/*", "图片文件")
    .replace("application/pdf", "PDF")
    .replace("application/vnd.ms-excel", "xls")
    .replace(
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      "xlsx"
    );

  return `支持格式：${types}，最大不超过${props.maxSize}MB`;
});

// 文件验证
const validateFile = (file: File): boolean => {
  const validType = props.fileTypes.some((t) => {
    if (t.endsWith("/*")) {
      return file.type.startsWith(t.split("/")[0]);
    }
    return file.type === t;
  });

  const validSize = file.size / 1024 / 1024 <= props.maxSize;

  if (!validType) {
    ElMessage.error(`不支持 ${file.type} 文件类型, 仅支持上传${tipText.value}`);
    return false;
  }

  if (!validSize) {
    ElMessage.error(`文件大小超过${props.maxSize}MB限制`);
    return false;
  }

  return true;
};

// 选择文件后立即上传
const handleImmediateUpload: UploadProps["onChange"] = (file) => {
  if (!file) return;
  // 重置文件列表（核心修复）
  fileList.value = []  // 清空历史记录

  if (validateFile(file.raw!)) {
    progressVisible.value = true;
    customUpload({ file: file.raw! });
  }
};

// 自定义上传实现
const customUpload = async (options: { file: File }) => {
  try {
    const form = new FormData();
    form.append("file", options.file);

    const res = await fileApi.uploadFiles(form, props.url, (e) => {
      progressPercent.value = Math.round((e.loaded * 100) / (e.total || 1));
    });
    if (res.code === 200) {
      progressStatus.value = "success";
      ElMessage.success("上传成功");
      // 重置文件列表（核心修复）
      fileList.value = []  // 清空历史记录
    } else {
      progressStatus.value = "exception";
      ElMessage.error("上传失败" + res.message);
      // 重置文件列表（核心修复）
      fileList.value = []  // 清空历史记录
    }
  } catch (err) {
    progressStatus.value = "exception";
    ElMessage.error("上传失败");
    // 重置文件列表（核心修复）
    fileList.value = []  // 清空历史记录
  } finally {
    setTimeout(() => (progressVisible.value = false), 2000);
  }
};
</script>

<style scoped>

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
}

.el-progress {
  margin-top: 10px;
  width: 300px;
}
</style>
